package xukj;

import xukj.network.Trans;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @ClassName App
 * @Description
 * @Author xukj
 * @Date 2019/1/9 15:54
 * @Version
 */
public class Server {


    public static void main(String[] args) {
        Socket socket = null;
        try (ServerSocket serverSocket = new ServerSocket(9001)){
            System.out.println("server run");
            while (true) {
                socket = serverSocket.accept();
                try {
                    ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                    Trans trans = (Trans) objectInputStream.readObject();

                    String className = trans.getClazz();
                    String methodStr = trans.getMethod();
                    Object[] params = trans.getParams();
                    Class<?>[] paramTypes = trans.getParamTypes();
                    Class<?> clazz = Class.forName(className+"Impl");
                    Method method = clazz.getMethod(methodStr, paramTypes);
                    Object obj = method.invoke(clazz.newInstance(), params);
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                    objectOutputStream.writeObject(obj);

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}